from rest_framework import serializers
from .models import Product
from .models import ProductCityRelation
from core.tools.serializers import ProvinceSerializer, CitySerializer


class ProductSerializers(serializers.ModelSerializer):
    pk = serializers.SerializerMethodField()
    adv = serializers.SerializerMethodField()
    price = serializers.SerializerMethodField()
    parent_product = serializers.SerializerMethodField()
    price_type = serializers.SerializerMethodField()
    active_desc = serializers.SerializerMethodField()

    # ppk = serializers.SerializerMethodField()

    # price_info = serializers.SerializerMethodField()
    # price1 = serializers.SerializerMethodField()
    # price2 = serializers.SerializerMethodField()
    # price3 = serializers.SerializerMethodField()
    # price_is_0 = serializers.SerializerMethodField()

    def get_active_desc(self, obj):
        if obj.active_desc:
            active_desc_list = obj.active_desc.split(';')
            return active_desc_list
        else:
            return []

    def get_pk(self, obj):
        return obj.id

    # def get_price_info(self, obj):
    #     price_info = obj.channelproduct_set.first().priceupdate_set.first()
    #     return price_info

    def get_price(self, obj):
        price_info = obj.channelproduct_set.first().priceupdate_set.first()
        if price_info:
            price_type = price_info.price_type
            obj.price_info = price_info
            if price_type == 1:
                return '%.0f' % price_info.price + "元"
            else:
                return '%.2f' % (price_info.price * 100)
        else:
            return ""

    def get_price_type(self, obj):
        price_info = obj.channelproduct_set.first().priceupdate_set.first()
        if price_info:
            if price_info.price_type == 1:
                return "直推奖（元）"
            else:
                return "直推奖（%）"
        else:
            return ""

    def get_adv(self, obj):
        return obj.adv.split(";")

    def get_parent_product(self, obj):
        if obj.product_set.exists() and obj.sign_type == 4:
            parent_product = True
        else:
            parent_product = False
        return parent_product

    class Meta:
        model = Product
        fields = ("id", "name", "special", "adv", "list_logo", "index_logo", "img", "price_type",
                  "price", "jump_status", "sign", "url", "parent_product", "api_type", "sign_type",
                  "jump_status", "pk", "active_desc", "banner", "is_firm")


class ProductCityRelationSerializers(serializers.ModelSerializer):
    product = ProductSerializers(many=False)
    province = ProvinceSerializer(many=False)
    city = CitySerializer(many=False)

    class Meta:
        model = ProductCityRelation
        fields = "__all__"


